$(function () {
    var content = $('#content');
    var status = $('#status');
    var message_input = $('#message');
    var user_id  = $('#user_id').val();
    var helper_id = $('#helper_id').val();
    var user_name  = $('#user_name').val();
    var helper_name = $('#helper_name').val();
    var user_type =$('#user_type').html();
    var from_user_id = function(){
        if(user_type=='helper')
            return helper_id;
        return user_id;
    }

    //建立websocket连接
    socket = io.connect('http://helper.paintmore.cn:3000',{"reconnect":true,"auto connect":true,"force new connection":true});
    if(user_type=='public'){
        socket.emit('bind',{user_id:user_id,helper_id:helper_id,user_name:user_name});
    }else{
        socket.on('bindUser', function (data){
            console.log(data);
            $('#user_id').val(data.user_id);
            $('#user_name').val(data.user_name);
        })
        socket.on('userExit', function (data){
            alert('user exit')
            $('#user_id').val(0);
            $('#user_name').val("");
        })
    }
    //收到server的连接确认
    socket.on('open', function () {
        console.log('已经连接上');
    });
    message_input.keydown(function (e) {
        if (e.keyCode === 13) {
            if(user_type=='helper' && $('#user_id').val()==0){
                alert('暂时没有用户连接');
                return ;
            }
            var msg = $(this).val();
            if (!msg) return;
            msg = {msg:msg,user_type:user_type,helper_name:helper_name,helper_id:helper_id,user_name:user_name,user_id:user_id};
            console.log(msg);
            socket.emit('message',msg);
            var p = '<p style="text-align:right;width: 100%;"><span style="">我</span>  : ' + msg.msg + '</p>';
            content.append(p)
            $(this).val('');
        }
    });

//监听message事件，打印消息信息
    socket.once('messages', function (json) {
        console.log(json)
        var p = '<p><span style="">' + json.form_user_id + '</span> @ ' + json.time + ' : ' + json.message + '</p>';
        if(json.to_user_id==from_user_id()){
            content.append(p)
        }
    });
});